var displayStream = {
	mimeCodec: 'video/webm;codecs=vp9,opus',
	isRecorder: false,
	time: 60,
	topic: null,
	number: 0,
	displayMedia: function(topic) {
		displayStream.topic = topic;
		// 调用用户媒体设备
		if (navigator.mediaDevices.getDisplayMedia) {
			displayStream.getDisplayMedia({video:true}, function(MediaStream) {
				displayStream.mediaStream = MediaStream;
				// 订阅目标的消息
				websocket.subscribe(displayStream.topic + "-toDisplay", function(msg) {
					var data = JSON.parse(msg.body);
					if (data.command == "createMediaRecorder") {
						if (displayStream.isRecorder) {
							displayStream.isRecorder = false;
							// 状态为recording时才进行停止
							if(displayStream.mediaRecorder.state == 'recording'){
								displayStream.mediaRecorder.stop();
							}
						}
						displayStream.createMediaRecorder(displayStream.topic);
					}
				});
				//displayStream.createMediaRecorder(displayStream.topic);
			}, function(err) {
				console.log(err);
			});
		}
	},
	// 推流
	createMediaRecorder: function(topic) {
		var options = {
			//audioBitsPerSecond : 128000,
			videoBitsPerSecond: 407040, // 848 x 480
			//videoBitsPerSecond: 921600, // 1280 x 720
			//videoBitsPerSecond: 1105920,
			mimeType: displayStream.mimeCodec
		}
		websocket.send(topic + "-toShow", JSON.stringify({ "command": "createMediaSource" }));
		displayStream.mediaRecorder = new MediaRecorder(displayStream.mediaStream, options);
		displayStream.isRecorder = true;
		setTimeout(function() {
			displayStream.number = 0;
			// 状态为inactive才进行启动
			if(displayStream.mediaRecorder.state == 'inactive'){
				displayStream.mediaRecorder.start(displayStream.time);
			}
		}, 30);
		displayStream.mediaRecorder.ondataavailable = function(e) {
			// 将内存里面的视频流数据转成ArrayBuffer
			var reader = new FileReader();
			reader.onloadend = function() {
				if (reader.result.byteLength > 0) {
					var buf = new Uint8Array(reader.result);
					// 发送视频流信息
					if (displayStream.isRecorder) {
						console.log(buf);
						websocket.send(topic, buf, true, { "number": displayStream.number });
						displayStream.number++;
					}
				}
				reader = null;
			}
			reader.readAsArrayBuffer(e.data);
		}
	},
	// 屏幕共享
	getDisplayMedia: function(constraints, success, error) {
		navigator.mediaDevices.getDisplayMedia(constraints).then(success).catch(error);
	}
}